package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    @Before(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        //joinPoint参数：连接点参数，表示当前正在执行的目标方法
        String name = joinPoint.getSignature().getName();//从获取的签名中获取方法名
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("[前置通知]："+name+"方法开始，参数为:"+args);
    }

    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))",returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint,Object result){
        String name = joinPoint.getSignature().getName();//从获取的签名中获取方法名
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("[返回通知]："+name+"方法执行成功结束，参数为:"+args+",返回值为:"+result);
    }

    @After(value =  "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();//从获取的签名中获取方法名
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("[后置通知]："+name+"方法完全结束，参数为:"+args);
    }

    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))",throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint,Throwable ex){
        String name = joinPoint.getSignature().getName();//从获取的签名中获取方法名
        String args = Arrays.toString(joinPoint.getArgs());
        String message = ex.getMessage();
        System.out.println("[异常通知]："+name+"方法抛出异常，参数为:"+args+",异常信息为:"+message);
    }

    @Around(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint)  {
        Object result=null;
        try {
            //前置通知
            System.out.println("前置通知");
            //执行目标方法
            result = joinPoint.proceed();
            //返回通知
            System.out.println("返回通知");
        }catch (Throwable e){
            //异常通知
            System.out.println("异常通知"+e.getMessage());
        }finally {
            System.out.println("后置通知");
        }
        return result;
    }

}
